import 'dart:convert';
import 'dart:developer';
import 'dart:typed_data';
import 'package:shen_nai/entity/data_entity.dart';
import 'package:shen_nai/eventbus/event_bus.dart';
import 'package:uuid/uuid.dart';
import 'package:web_socket_channel/io.dart';

class WebSocketManage {
  static WebSocketManage? _instance;

  WebSocketManage._internal() {
    connect();
  }

  factory WebSocketManage() {
    _instance ??= WebSocketManage._internal();
    return _instance!;
  }

  late IOWebSocketChannel _channel;

  connect() {
    _channel = IOWebSocketChannel.connect(
        'ws://cloud.alientek.com/connection/6138ea6002b1472a88fe3e404f54708c/org/2896?token=${const Uuid().v1()}');
    _channel.stream
        .listen(onData, onDone: onDone, onError: onError, cancelOnError: false);
  }

  //订阅
  subscription(String deviceNum) {
    List<int> list = [0x01];
    list.addAll(utf8.encode(deviceNum));
    sendMessage(utf8.decode(list));
  }

  //取消订阅
  unSubscription(String deviceNum) {
    List<int> list = [0x02];
    list.addAll(utf8.encode(deviceNum));
    sendMessage(utf8.decode(list));
  }

  //发送消息
  sendMessage(String message) {
    _channel.sink.add(message);
  }

  //数据回调
  onData(event) {
    //log(event.length.toString());
    var data = event as Uint8List;
    // ignore: unrelated_type_equality_checks
    if (data.isNotEmpty &&
        data.length >= 174 &&
        data.sublist(0, 1)[0] == 0x06) {
      //订阅的设备发送消息
      //设备号
      String devicesNum = String.fromCharCodes(data.sublist(1, 21));
      //A累计电量
      int aPower = ((data[28] & 0x07) *
              16777216 + // & 31 去除高五位 *65536*256 左移24位 24-27bit(位)
          data[29] * 65536 + // 16-23bit(位)
          data[30] * 256 + // 8-15bit(位)
          data[31]); // 0-7bit(位)
      //A累计时间
      int aTime = data[32] * 256 + data[33];

      List shisiweimoniliangData = data.sublist(34, 174);
      // 140个开关量
      List<int> switchData = List.filled(140, 0);
      // 十四位模拟量，40个，范围0-16383
      List<int> moniliang14 = List.filled(40, 0);
      for (int i = 0; i < 40; i++) {
        moniliang14[i] = ((shisiweimoniliangData[i * 2] & 0x3f) << 8) +
            shisiweimoniliangData[i * 2 + 1];
        switchData[i * 2] = shisiweimoniliangData[i * 2] >> 7;
        switchData[i * 2 + 1] = (shisiweimoniliangData[i * 2] >> 6) & 1;
      }
      // 七位模拟量，60个，范围0-127
      List<int> moniliang7 = List.filled(60, 0);
      for (int i = 0; i < 30; i++) {
        moniliang7[i * 2] = ((shisiweimoniliangData[i * 2 + 80] & 0x3f) << 1) +
            ((shisiweimoniliangData[i * 2 + 81] & 0x80) >> 7);
        moniliang7[i * 2 + 1] = shisiweimoniliangData[i * 2 + 81] & 0x7f;
        switchData[i * 2 + 80] = shisiweimoniliangData[i * 2 + 80] >> 7;
        switchData[i * 2 + 81] = (shisiweimoniliangData[i * 2 + 80] >> 6) & 1;
      }
      // B累计电量
      int bPower = moniliang14[38] * 10000 + moniliang14[39];
      // B累计时间
      int bTime = moniliang14[32] + ((moniliang14[37] & 0x3000) << 2);

      DataEntity dataEntity = DataEntity(
          devicesNum,
          aPower.toString(),
          aTime.toString(),
          bPower.toString(),
          bTime.toString(),
          moniliang14,
          moniliang7,
          switchData);
      eventBus.fire(EquipmentInformationEvent(dataEntity));
    }
  }

  onError(e) {
    log(e.toString());
    //dispose();
  }

  onDone() {
    log('webSocket断开连接');
    //dispose();
  }

  dispose() {
    _channel.sink.close();
  }
}
